/*
 * GlobalCtrl includes:
 * 		Login management
 * 		Message system
 */
var GlobalCtrl = dojo.declare("FidoWeb.GlobalCtrl", null, {
	//constructor/destructor
	constructor : globalCtrl_contructor,
	destroy : globalCtrl_destructor,
	
	//methods
	curSchool : globalCtrl_curSchool,
	init : globalCtrl_init,
	logout : globalCtrl_logout,
	schools : globalCtrl_schools,
	setCurSchool : globalCtrl_setCurSchool
});

function globalCtrl_contructor(){
	this._schools = new Array();
}

function globalCtrl_destructor(){
}

function globalCtrl_curSchool(){
	var obj = this;
	if (isNaN(getCookie("global.school.id"))){
		setCookie("global.school.id", 0);
		return 0;
	}  else {
		var id = getCookie("global.school.id");
		for (var i = 0; i < obj._schools.length; i ++)
			if (obj._schools[i].id == id) return i;
		return 0;
	}
}

function globalCtrl_init(){
	var obj = this;
	obj._schools = jQuery.parseJSON($(".page_variable div[var_name='schools']").html());
}

function globalCtrl_logout(){
	$.getJSON("/login/logout", function(data){
		window.location.reload();
	});
}

function globalCtrl_schools(){
	var obj = this;
	return obj._schools;
}

function globalCtrl_setCurSchool(curSchool){
	var obj = this;
	setCookie("global.school.id", curSchool);
	window.location.reload();
}

/*
 * Configuration of floater's parameter
 * 		name : the name of a floater
 * 		pagePadding : default 10
 * 		defaultLook
 * 		hideLook
 * 		loadingLook
 * 		z_index: default 0
 * 
 * States of GlobalFloater
 * 		hidden
 * 		showingLoading
 * 		showingDefault
 */
var GlobalFloaterCount = 0;
var GlobalFloater = dojo.declare(null, {
	//constructor/destructor
	constructor : globalFloater_constructor,
	destroy : globalFloater_destructor,
	
	//methods
	hide : globalFloater_hide,
	setDefaultHtml : globalFloater_setDefaultHtml,
	setDefaultLook : globalFloater_setDefaultLook,
	setHideLook : globalFloater_setHideLook,
	setLoadingLook : globalFloater_setLoadingLook,
	showLoading : globalFloater_showLoading,
	showDefault : globalFloater_showDefault,
	
	//signals
	sizeChanged : globalFloater_sizeChanged
});

function globalFloater_show_p(eventId, para, callback){
	var obj = this;
	if (para == null) para = {};
	if (para.look == null) para.look = {};
	if (para.duration == null) para.duration = "normal";
	
	if (obj._eventId != this._eventId) return;
	obj._html.fadeIn(function(){
		if (obj._eventId != eventId) return;
		obj._html.animate(para.look, para.duration, function(){
			if (callback != null) callback();
			obj.sizeChanged();
		});
	});
}

function globalFloater_constructor(parameter){
	if (parameter == null) parameter = {};
	
	if (parameter.name == null) parameter.name = "floater_" + GlobalFloaterCount;
	this._parameter = parameter;
	if (this._parameter.pagePadding == null) this._parameter.pagePadding = 10;
	if (this._parameter.z_index == null) this._parameter.z_index = 0;
	
	$("body").append("<div class='global_floater' style='display:none;' id='" + parameter.name + "'></div>");
	this._html = $("#" + "floater_" + GlobalFloaterCount);
	this._html.css("z-index", this._parameter.z_index);
	this._html.css("position", "absolute");
	this._html.css("background-color", "white");
	this._html.animate(parameter.hideLook, 0);
	
	this._html.append("<div id='floater_content'></div>");
	this._content = this._html.find("#floater_content");
	this._content.css("position", "absolute");
	this._content.css("overflow", "auto");
	this._content.css("left", this._parameter.pagePadding + "px");
	this._content.css("right", this._parameter.pagePadding + "px");
	this._content.css("bottom", this._parameter.pagePadding + "px");
	this._content.css("top", this._parameter.pagePadding + "px");
	
	this._defaultHtml = "";
	
	this._state = "hidden";
	this._eventId = 0;
	
	this.show_p = globalFloater_show_p;
	GlobalFloaterCount ++;
}

function globalFloater_destructor(){
	this._html.remove();
}

function globalFloater_hide(){
}

function globalFloater_setDefaultHtml(html){
	this._defaultHtml = html;
}

function globalFloater_setDefaultLook(look){
	var obj = this;
	obj._parameter.defaultLook = look;
	var eventId = ++ obj._eventId;
	if (obj._state == "showingDefault")
		obj.show_p(eventId, {look : obj._parameter.defaultLook, duration : "slow"});
}

function globalFloater_setHideLook(look){
	var obj = this;
	obj._parameter.hideLook = look;
	var eventId = ++ obj._eventId;
	if (obj._state == "hidden")
		obj.show_p(eventId, {look : obj._parameter.hideLook, duration : "slow"});
}

function globalFloater_setLoadingLook(look){
	var obj = this;
	obj._parameter.loadingLook = look;
	var eventId = ++ obj._eventId;
	if (obj._state == "showingLoading")
		obj.show_p(eventId, {look : obj._parameter.loadingLook, duration : "slow"});
}

function globalFloater_showLoading(callback){
	var obj = this;
	var eventId = ++ this._eventId;
	obj._state = "showingLoading";
	obj._content.fadeOut(function(){
		if (obj._eventId != eventId) return;
		obj._content.html("<div><img src='/image/global/loading.gif'></img></div>");
		obj._content.fadeIn();
	});
	obj.show_p(eventId, {look : obj._parameter.loadingLook, duration : "slow"}, function(){
		if (callback != null) callback();
	});
}

function globalFloater_showDefault(callback){
	var obj = this;
	var eventId = ++ this._eventId;
	obj._content.fadeOut();
	obj._state = "showingDefault";
	obj.show_p(eventId, {look : this._parameter.defaultLook, duration : "slow"}, function(){
		if (obj._eventId != eventId) return;
		obj._content.html(obj._defaultHtml);
		obj._content.fadeIn();
		if (callback != null) callback();
	});
}

function globalFloater_sizeChanged(){
}

/*
 * A list with tabs:
 * 		parameter:
 * 			baseItem
 * 			listName
 * 			defaultTab
 * 			normalTabHtml
 * 			currentTabHtml
 * 			headerHidden : default FALSE
 * 			tabHidden : default FALSE
 * 			tabs : an array [tabName, tabItemsUrl, tabItemsUrlPost, tabItemCountUrl, tebItemCountUrlPost]
 * 			itemHtml
 * 			itemHtmlMapping : an array [arrayId, itemHtmlId, htmlType]
 * 			contentAppending : change the height of list while its content changes, default FALSE
 */
var TabListCount = 0;
var TabList = dojo.declare(null, {
	//constructor/destructor
	constructor : tabList_constructor,
	destructor : tabList_destructor,
	
	//methods
	curTab : tabList_curTab,
	init : tabList_init,
	showTab : tabList_showTab,
	update : tabList_update
});

function tabList_constructor(){
	this._curTab = -1;
	this._pageItemCount = 10;
	this._isLoading = false;	
	this._listItemStart = 0;
	this._listItemTotal = 0;
	
	this._setLastEnabled = tabList_setLastEnabled;
	this._setNextEnabled = tabList_setNextEnabled;
	this._setTabHtml = tabList_setTabHtml;
	this._showList = tabList_showList;
}

function tabList_destructor(){
}

function tabList_curTab(){
	return this._curTab;
}

function tabList_init(parameter){
	var obj = this;
	
	if (parameter == null) obj._parameter = {};
	else obj._parameter = parameter;
	if (obj._parameter.tabHidden == null) obj._parameter.tabHidden = false;
	if (obj._parameter.headerHidden == null) obj._parameter.headerHidden = false;
	else if (obj._parameter.headerHidden) obj._parameter.tabHidden = true;
	if (obj._parameter.isTable == null) obj._parameter.isTable = false;
	
	obj._parameter.baseItem.html("");
	obj._parameter.baseItem.append('<div class="tablist" id="tablist_' + TabListCount + '" style="width:100%;"></div>');
	var tablist = obj._parameter.baseItem.find("#tablist_" + TabListCount);
	TabListCount ++;
	
	tablist.append('<h2></h2>');
	var header = tablist.find("h2");
	header.append('<div id="list_title" style="float:left;line-height:30px;"></div>');
	obj._title = header.find("#list_title");
 	header.append('<div id="list_tab" style="padding:0 0 0 40px;float:left;line-height:30px;"></div>');
	obj._tab = header.find("#list_tab");
	header.append('<div id="list_pager_next" style="height:20px;width:30px;margin:5px;float:right;background-image:url(/image/global/button_tablist_next_disabled.gif);"></div>');
	obj._pagerNext = header.find("#list_pager_next");
	header.append('<div id="list_pager_page" style="line-height:20px;font-size:13px;float:right;padding:5px 0 5px 0;">?/?</div>');
	obj._pagerPage = header.find("#list_pager_page");
	header.append('<div id="list_pager_last" style="height:20px;width:30px;margin:5px;float:right;background-image:url(/image/global/button_tablist_last_disabled.gif);"></div>');
	obj._pagerLast = header.find("#list_pager_last");
	if (obj._parameter.headerHidden) header.hide();
	
	tablist.append('<div id="list_content_bound" style="float:left;position:relative;width:100%;min-height:40px;"></div>');
	var contentBound = tablist.find("#list_content_bound");
	if (obj._parameter.headerHidden) contentBound.css("top", "0");
	contentBound.append('<div id="list_loading" style="left:0;top:0;width:100%;height:100%;background-color:white;position:absolute;"><img src="/image/global/loading.gif"></img></div>');
	obj._loading = contentBound.find("#list_loading");
	if (obj._parameter.isTable) contentBound.append('<div id="list_content" style="opacity:0.01;"><table style="width:100%;"><tbody style="width:100%;"></tbody></table></div>');
	else contentBound.append('<div id="list_content" style="opacity:0.01;width:100%;"></div>');
	obj._content = contentBound.find("#list_content");
	
	obj._title.html(obj._parameter.listName);
	
	obj.showTab(obj._parameter.defaultTab);
}

function tabList_showTab(id){
	var obj = this;
	if (obj._isLoading || obj._curTab == id) return;
	
	obj._curTab = id;
	if (!obj._parameter.tabHidden) obj._setTabHtml();
	
	obj._showList(0);
}

function tabList_update(){
	this._showList(0);
}

function tabList_setLastEnabled(enabled){
	var obj = this;
	obj._pagerLast.unbind();
	if (enabled){
		obj._pagerLast.css("background-image", "url(/image/global/button_tablist_last.gif)");
		obj._pagerLast.css("cursor", "pointer");
		obj._pagerLast.click(function(){
			obj._showList(obj._listItemStart - obj._pageItemCount);
		});
	}  else {
		obj._pagerLast.css("background-image", "url(/image/global/button_tablist_last_disabled.gif)");
		obj._pagerLast.css("cursor", "default");
	}  
}

function tabList_setNextEnabled(enabled){
	var obj = this;
	obj._pagerNext.unbind();
	if (enabled){
		obj._pagerNext.css("background-image", "url(/image/global/button_tablist_next.gif)");
		obj._pagerNext.css("cursor", "pointer");
		obj._pagerNext.click(function(){
			obj._showList(obj._listItemStart + obj._pageItemCount);
		});
	}  else {
		obj._pagerNext.css("background-image", "url(/image/global/button_tablist_next_disabled.gif)");
		obj._pagerNext.css("cursor", "default");
	}  
}

function tabList_setTabHtml(){
	var obj = this;
	obj._tab.html("");
	for (var i = 0; i < obj._parameter.tabs.length; i ++){
		var curTab = obj._parameter.tabs[i];
		if (i == obj._curTab){
			obj._tab.append("<span id='tab_" + i + "' arrayId='" + i + "' style='float:left;'>" + obj._parameter.currentTabHtml + "</span>");
		}  else {
			obj._tab.append("<span id='tab_" + i + "' arrayId='" + i + "' style='float:left;'>" + obj._parameter.normalTabHtml + "</span>");
		}  
		var t = obj._tab.find("#tab_" + i);
		t.find("#tab_name").html(curTab[0]);
		t.click(function(){
			obj.showTab($(this).attr("arrayId"));
		});
		if (i + 1 < obj._parameter.tabs.length){
			obj._tab.append("<div style='float:left;padding:0 5px 0 5px;font-weight:bold;'>·</div>");
		}
	}
}

function tabList_showList(start){
	var obj = this;
	var curTab = obj._parameter.tabs[obj._curTab];
	var readyCount = 2;
	if (obj._isLoading) return;
	
	obj._listItemStart = start;
	obj._pagerPage.html("?/?");
	obj._setLastEnabled(false);
	obj._setNextEnabled(false);
	function showIt(){
		readyCount --;
		if (readyCount == 0){
			obj._content.animate({opacity : 1.0}, function(){
				obj._pagerPage.html((obj._listItemStart / obj._pageItemCount + 1) + "/" + Math.max(1, Math.ceil(obj._listItemTotal / obj._pageItemCount)));
				if (obj._listItemStart > 0) obj._setLastEnabled(true);
				if (obj._listItemStart + obj._pageItemCount < obj._listItemTotal) obj._setNextEnabled(true);
				obj._isLoading = false;
			});
		}
	}
	
	obj._isLoading = true;
	obj._content.stop().animate({opacity : 0.01});
	obj._loading.stop();
	obj._loading.css("opacity", 1.0);
	obj._loading.fadeIn(function(){
		var para = curTab[2];
		para["start"] = start;
		para["end"] = start + obj._pageItemCount;
		$.getJSON(curTab[1], para, function(data){
			obj._loading.stop();
			obj._loading.css("opacity", 1.0);
			obj._loading.fadeOut();
			if (data.length == 0){
				obj._content.html(obj._parameter.emptyHtml[obj._curTab]);
			}  else {
				if (obj._content.find("#list_item_0").size() == 0){
					if (obj._parameter.isTable) obj._content.html('<table style="width:100%;"><tbody style="width:100%;"></tbody></table>');
					else obj._content.html("");
				}
				for (var i = 0; i < data.length; i ++){
					if (obj._content.find("#list_item_" + i).size() == 0){
						if (obj._parameter.isTable) obj._content.find("tbody").append("<tr id='list_item_" + i + "'>" + obj._parameter.itemHtml[obj._curTab] + "</tr>");
						else obj._content.append("<div id='list_item_" + i + "' style='width:100%;'>" + obj._parameter.itemHtml[obj._curTab] + "</div>");
					}  else {
						if (obj._parameter.isTable) obj._content.find("#list_item_" + i).html(obj._parameter.itemHtml[obj._curTab]);
						else obj._content.find("#list_item_" + i).html(obj._parameter.itemHtml[obj._curTab]);
					}  
					var item = obj._content.find("#list_item_" + i);
					for (var j = 0; j < obj._parameter.itemHtmlMapping[obj._curTab].length; j ++){
						var curItemEle = obj._parameter.itemHtmlMapping[obj._curTab][j];
						var curItemHtml = item.find("#" + curItemEle[1]);
						if (curItemEle[2] == "text") curItemHtml.html(data[i][curItemEle[0]]);
						else if (curItemEle[2] == "img") curItemHtml.attr("src", data[i][curItemEle[0]]);
						else if (curItemEle[2] == "attr_id") curItemHtml.attr("alt", data[i][curItemEle[0]]);
						else if (curItemEle[2] == "link"){
							curItemHtml.unbind();
							curItemHtml.click(function(){
								if (curItemEle[0] != null) curItemEle[0]($(this));
							});
							curItemHtml.attr("href", data[i][curItemEle[0]]);
						}  else if (curItemEle[2] == "star"){
							curItemHtml.html("");
							curItemHtml.append("<div class='current-rating' style='width:" + 15 * parseInt(data[i][curItemEle[0]]) + "px;'></div>");
						}
					}
					item.unbind();
					item.click(function(){
						if (obj._parameter.itemClicked != null) obj._parameter.itemClicked($(this));
					});
				}
			}
			
			for (var i = data.length; i < obj._pageItemCount; i ++)
				if (obj._content.find("#list_item_" + i).size() > 0) obj._content.find("#list_item_" + i).remove();
			showIt();
		});
		
		$.getJSON(curTab[3], curTab[4], function(data){
			obj._listItemTotal = data[0];
			showIt();
		});
	});
}

$.fn.rater = function(url, options, callback){
	if (url == null) return;
	var settings = {url : url, maxvalue : 5, curvalue : 0};
	
	if (options) $.extend(settings, options);
	$.extend(settings, {cancel: (settings.maxvalue > 1) ? true : false});
	
	var container = $(this);
	$.extend(container, {averageRating: settings.curvalue, url: settings.url});
	
	if (settings.getParameter == null) setting.getParameter = {};

	if (!settings.style || settings.style == null || settings.style == 'basic'){
		var raterwidth = settings.maxvalue * 15;
		var ratingparent = '<ul class="star-rating" style="width:' + raterwidth + 'px">';
	}
	if (settings.style == 'small'){
		var raterwidth = settings.maxvalue * 10;
		var ratingparent = '<ul class="star-rating small-star" style="width:'+raterwidth+'px">';
	}
	if (settings.style == 'inline'){
		var raterwidth = settings.maxvalue * 10;
		var ratingparent = '<span class="inline-rating"><ul class="star-rating small-star" style="width:'+raterwidth+'px">';
	}
	container.append(ratingparent);
	
	var starWidth, starIndex, listitems = '';
	var curvalueWidth = Math.floor(100 / settings.maxvalue * settings.curvalue);
	for (var i = 0; i <= settings.maxvalue ; i ++){
		if (i == 0){
			listitems += '<li class="current-rating" style="width:'+curvalueWidth+'%;">' + settings.curvalue + '/' + settings.maxvalue + '</li>';
		}  else {
			starWidth = Math.floor(100 / settings.maxvalue * i);
			starIndex = (settings.maxvalue - i) + 2;
			listitems += '<li class="star"><a href="#' + i + '" title="'+ i +'/' + settings.maxvalue + '" style="width:' + starWidth + '%;z-index:' + starIndex+'">' + i + '</a></li>';
		}
	}
	container.find('.star-rating').append(listitems);

	if (settings.maxvalue > 1) container.append('<span class="star-rating-result"></span>'); 
	var stars = $(container).find('.star-rating').children('.star');
	stars.click(function(){
		if (settings.maxvalue == 1){
			settings.curvalue = (settings.curvalue == 0) ? 1 : 0;
			$(container).find('.star-rating').children('.current-rating').css({width:(settings.curvalue*100)+'%'});
			var para = settings.getParameter;
			para.rating = settings.curvalue;
			$.getJSON(container.url, para, function(response){
				if (response == "success" && callback != null) callback(para.rating);
			});
		}  else {
			settings.curvalue = stars.index(this) + 1;
			raterValue = $(this).children('a')[0].href.split('#')[1];
			var para = settings.getParameter;
			para.rating = raterValue;
			$.getJSON(container.url, para, function(response){
				if (response == "success") container.children('.star-rating-result').html("打分成功！");
				else container.children('.star-rating-result').html("打分失败！");
				if (response == "success" && callback != null) callback(para.rating);
			});
		}
		return false;
	});
	return this;
}

function setCookie(c_name, value, expiredays){
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
}

function getCookie(c_name){
	if (document.cookie.length > 0){
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1){
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return "";
}

if (dojo.getObject("globalCtrl") == null) var globalCtrl = new GlobalCtrl;
$(document).ready(function(){
	globalCtrl.init();
});
function uStrlen(s){
	var ret = 0;
	for (var i = 0; i < s.length; i ++){
		if (s.charCodeAt(i) > 127) ret += 2;
		else ret ++;
	}
	return ret;
}

function isValidMobile(mobile){
	if (uStrlen(mobile) != 11) return false;
	for (var i = 0; i < mobile.length; i ++)
		if (mobile[i] < '0' || mobile[i] > '9') return false;
	if (mobile < "13000000000" || mobile > "19000000000") return false;
	return true;
}

function isValidFidocard(fidocard){
	if (uStrlen(fidocard) != 13) return false;
	for (var i = 0; i < fidocard.length; i ++)
		if (fidocard[i] < '0' || fidocard[i] > '9') return false;
	return true;
}
	
function isValidName(username){
	if (uStrlen(username) < 4 || uStrlen(username) > 16) return false;	
	for (var i = 0; i < username.length; i ++){
		var c = username.charCodeAt(i);
		if (!((c <= 0x9fff && c >= 0x4e00) || (c >= 48 && c <= 57)  || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 32)) return false;
	}
	return true;
}

function isValidPassword(password){
	if (password.length < 6 || password.length > 16) return false;
	for (var i = 0; i < password.length; i ++){
		var c = password.charCodeAt(i);
		if (!((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95 || c == 32)) return false;
	}
	return true;
}

function isValidEmail(email){
	regExp = /^[a-zA-Z]+([_\.-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*(\.[a-zA-Z]{2,4})+$/;
	return email.search(regExp) != -1;
} 

function trimContent(text){
	text = text.replace(new RegExp("&", "g"), "&amp;");
	text = text.replace(new RegExp(" ", "g"), "&nbsp;");
	text = text.replace(new RegExp("<", "g"), "&lt;");
	text = text.replace(new RegExp(">", "g"), "&gt;");
	text = text.replace(new RegExp("\"", "g"), "&quot;");
	text = text.replace(new RegExp("\r\n", "g"), "<br/>");
	text = text.replace(new RegExp("\n", "g"), "<br/>");
	text = text.replace(new RegExp("<br/><br/>", "g"), "<br/>");
	return text;
}